package controller;

import domain.Goods;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.JDBCUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class IndexController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        try {
            conn = JDBCUtils.getDruidConnection();
            String sql = "select `id`,`name`,`price`,`num`,`img` from goods;";
            QueryRunner runner = new QueryRunner();
            BeanListHandler<Goods> handler = new BeanListHandler<>(Goods.class);
            List<Goods> goods = runner.query(conn, sql, handler);
            request.getSession().setAttribute("goods", goods);
            request.getRequestDispatcher("/pages/index/index.jsp").forward(request, response);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn,null);
        }
    }
}
